<template>
  <div class="flex flex-col justify-between flex-auto pt-4 bg-white">
    <div class="flex flex-col">
      <div
        v-if="showNotice"
        class="flex flex-row items-center justify-between bg-[#F0F6FF] px-4"
      >
        <div class="flex flex-row items-center py-2 text-sm w-full">
          <van-icon class="mr-[10px]" name="info" color="#436BFF"></van-icon>
          点击发言人，播放对应发言片段，让标注更简单！
        </div>
      </div>

      <div class="px-2">
        <div
          v-if="processedSpeechData.length > 0"
          class="mt-2 px-3 py-5 bg-[#F9FAFC] rounded-lg w-full"
        >
          <div
            v-for="speaker in processedSpeechData"
            :key="speaker.uid"
            @click.stop="handleShowSegment(speaker)"
            class="mb-5 last:mb-0"
          >
            <div class="flex mb-2">
              <div class="flex flex-row text-sm items-center">
                <div class="text-gray-800 mr-2 min-w-[38px]">{{ speaker.name }}</div>
                <div
                  class="text-gray-500 max-w-[170px] transition-all duration-200"
                  :class="
                    expandedMap[speaker.uid]
                      ? 'whitespace-normal break-words'
                      : 'whitespace-nowrap overflow-hidden text-ellipsis'
                  "
                >
                  {{ subTitle(speaker) }}
                </div>
                <button
                  v-if="shouldShowExpand(subTitle(speaker))"
                  class="ml-1 text-xs text-blue-500 focus:outline-none whitespace-nowrap"
                  @click.stop="toggleExpand(speaker.uid)"
                >
                  {{ expandedMap[speaker.uid] ? "收起" : "展开" }}
                </button>
              </div>
              <div
                v-if="enableEdit"
                @click.stop="handleEdit(speaker)"
                class="text-xs text-gray-500 ml-2 flex items-center"
              >
                <van-icon name="edit" class="mr-1" />
                <span class="min-w-[40px]">标注</span>
              </div>
              <div class="text-sm text-gray-500 ml-auto">
                {{ speaker.formattedPercent }}%
              </div>
            </div>
            <div class="relative w-full h-2 bg-gray-100 overflow-hidden">
              <div
                v-for="(block, blockIndex) in speaker.visualBlocks"
                :key="blockIndex"
                class="absolute h-full top-0"
                :style="{
                  left: `${(block.bt / totalDuration) * 100}%`,
                  width: `${(block.duration / totalDuration) * 100}%`,
                  backgroundColor: barColor(speaker),
                }"
              ></div>
            </div>
          </div>
        </div>
        <van-empty
          class="bg-white"
          v-if="processedSpeechData.length === 0"
          description="暂无内容"
        />
      </div>
    </div>

    <div v-if="!hiddenGenerateBtn" class="w-full px-2 mt-10 pb-12">
      <van-button
        size="large"
        color="#4D7CFE"
        :disabled="!enableGenerate"
        @click="handleGenerate"
        >{{ isGenerateSuccess ? "重新生成" : "开始生成" }}</van-button
      >
    </div>

    <van-popup
      v-model:show="showSegment"
      round
      position="bottom"
      teleport="#minutesPage"
      safe-area-inset-bottom
      closeable
    >
      <SpeechSegment
        v-if="showSegment"
        :userId="selectedUserId"
        @close="showSegment = false"
        @handleEdit="handleEdit"
      />
    </van-popup>

    <van-popup
      v-model:show="showBindCustomer"
      round
      position="bottom"
      teleport="#minutesPage"
    >
      <BindCustomer @onHide="showBindCustomer = false" />
    </van-popup>

    <EditParticipantInfo
      v-model:show="showEdit"
      :labelParticipantInfo="currentEditSpeaker"
      :changeItemSuccess="handleChangeSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { useMinutesStore } from "@/store";
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import { Icon as VanIcon, showToast } from "vant";
import { SpeechOverview, SpeechOverviewType, FormData } from "@/types/minutes/store.type";
import SpeechSegment from "./speechSegment.vue";
import EditParticipantInfo from "@/views/minutes/components/editParticipantInfo/index.vue";
import { EventBusEnum, GenerateStatus } from "@/types";
import BindCustomer from "@/views/minutes/components/editCustomer/BindCustomer.vue";
import EventBus from "@/EventBus";

const minutesStore = useMinutesStore();
const { speechOverviewData, totalDuration, outerFiledPartner } = storeToRefs(
  minutesStore
);

const isLabelAllParticipant = computed(() => minutesStore.isLabelAllParticipant);

const labelParticipantCount = computed(() => minutesStore.labelParticipantCount);

const generateStatus = computed(() => minutesStore.generateReportState.generateStatus);
const isGenerateSuccess = computed(() => generateStatus.value === GenerateStatus.SUCCESS);
const haveReLabel = computed(() => minutesStore.haveReLabel);

// 隐藏 生成成功的情况
const hiddenGenerateBtn = computed(() => {
  if (generateStatus.value === GenerateStatus.IN_PROCESS) {
    return true;
  }
  if (!minutesStore.isOwner) {
    return true;
  }
  return !haveReLabel.value && isGenerateSuccess.value;
});

// 是否可以生成报告
const enableGenerate = computed(() => {
  return isLabelAllParticipant.value;
});

const handleGenerate = async () => {
  await minutesStore.generateReportAction();
  EventBus.emit(EventBusEnum.CHANGE_TAB_MAIN, 2);
};

const colors = ["#4D7CFE", "#52C41A", "#FA541C", "#F5222D"];

const barColor = (speaker: SpeechOverview) => {
  if (speaker.type === SpeechOverviewType.CUSTOMER_ROLE) {
    return colors[0];
  } else if (speaker.type === SpeechOverviewType.INTERNAL_PARTNER) {
    return colors[1];
  } else {
    return colors[2];
  }
};

const speech_showNotice_key = "speech_showNotice";
const showNotice = ref(localStorage.getItem(speech_showNotice_key) !== "false");
const closeNotice = () => {
  showNotice.value = false;
  localStorage.setItem(speech_showNotice_key, false.toString());
};

const showBindCustomer = ref(false);
const showEdit = ref(false);
const currentEditSpeaker = ref();
const handleEdit = (speaker: SpeechOverview) => {
  if (generateStatus.value === GenerateStatus.IN_PROCESS) {
    showToast("报告正在生成中，请等待生成结束后再标注");
    return;
  }
  // //判断权限
  if (!minutesStore.isOwner) {
    showToast("您不是拥有者，没有权限标注");
    return;
  }
  if (minutesStore.isNeedBindCustomer) {
    showToast("请先绑定");
    showBindCustomer.value = true;
    return;
  }
  currentEditSpeaker.value = speaker;
  showEdit.value = true;
};

const showSegment = ref(false);
const selectedUserId = ref("");
const handleShowSegment = (speaker: SpeechOverview) => {
  EventBus.emit(EventBusEnum.AUDIO_PAUSE);
  selectedUserId.value = speaker.uid;
  showSegment.value = true;
};

const handleChangeSuccess = async () => {
  await minutesStore.fetchAllData();
  showEdit.value = false;
};

// 是否允许标注
const enableEdit = computed(() => minutesStore.isOwner);

const processedSpeechData = computed(() => {
  if (!speechOverviewData.value || !totalDuration.value) {
    return [];
  }

  // Increased merge threshold
  const mergeThreshold = totalDuration.value * 0.01;

  return speechOverviewData.value.map((speaker) => {
    if (!speaker.asrList || speaker.asrList.length === 0) {
      return {
        ...speaker,
        formattedPercent: Math.round(speaker.percent),
        visualBlocks: [],
      };
    }

    const sortedAsrList = [...speaker.asrList].sort((a, b) => a.bt - b.bt);
    const visualBlocks: { bt: number; et: number; duration: number }[] = [];

    if (sortedAsrList.length > 0) {
      let currentBlock = {
        bt: sortedAsrList[0].bt,
        et: sortedAsrList[0].et,
      };

      for (let i = 1; i < sortedAsrList.length; i++) {
        const nextAsr = sortedAsrList[i];
        const gap = nextAsr.bt - currentBlock.et;

        if (gap >= 0 && gap < mergeThreshold) {
          currentBlock.et = nextAsr.et;
        } else {
          visualBlocks.push({
            ...currentBlock,
            duration: currentBlock.et - currentBlock.bt,
          });
          currentBlock = { bt: nextAsr.bt, et: nextAsr.et };
        }
      }
      visualBlocks.push({
        ...currentBlock,
        duration: currentBlock.et - currentBlock.bt,
      });
    }

    const minWidthThreshold = totalDuration.value * 0.002;
    const finalBlocks = visualBlocks.map((block) => ({
      ...block,
      duration: Math.max(block.duration, minWidthThreshold),
    }));

    return {
      ...speaker,
      formattedPercent: Math.round(speaker.percent < 1.0 ? 1.0 : speaker.percent),
      visualBlocks: finalBlocks,
    };
  });
});

const combinedFields = computed(() => {
  return outerFiledPartner.value.filter((v) => v.fieldStatus !== 0);
});

const getCustomerStatus = (formData: FormData | null, maxLength = 5) => {
  if (!formData) {
    return [];
  }
  let fieldValues = formData.fieldValues || [];
  let statusArray = [];
  for (const tempField of combinedFields.value) {
    const { fieldName } = tempField;
    const fieldValue = fieldValues.find((v) => v.fieldId === tempField.id)?.fieldValue;
    if (fieldValue) {
      statusArray.push(fieldName + ":" + fieldValue);
    }
  }

  if (statusArray.length > maxLength) {
    statusArray = statusArray.slice(0, maxLength);
    statusArray.push("...");
  }
  return statusArray;
};

const subTitle = (speaker: SpeechOverview) => {
  if (speaker.type === SpeechOverviewType.INTERNAL_PARTNER) {
    if (speaker.position) {
      return speaker.position;
    }
    return speaker.formData?.fieldValues
      .map((v) => v.fieldName + ":" + v.fieldValue)
      .join(" | ");
  }
  return getCustomerStatus(speaker.formData).join(" | ");
};

// 记录每个speaker的展开状态
const expandedMap = ref<{ [uid: string]: boolean }>({});

// 切换展开/收起
const toggleExpand = (uid: string) => {
  expandedMap.value[uid] = !expandedMap.value[uid];
};

// 判断是否需要显示"展开"按钮（比如内容长度大于15就显示）
const shouldShowExpand = (text: string | undefined) => {
  return !!text && text.length > 15; // 超过15个字就显示展开按钮
};
</script>

<style scoped lang="less">
/* Remove all previous styles and use Tailwind CSS */
</style>
